package com.example.mall_springboot_01.users.controller;


import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mall_springboot_01.users.entity.UmsAdmin;
import com.example.mall_springboot_01.users.service.IUmsAdminService;
import com.example.mall_springboot_01.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author gongxl
 * @since 2021-08-02
 */
@RestController
@RequestMapping("/users/ums-admin")
@Slf4j
public class UmsAdminController {
    @Autowired
    private IUmsAdminService iUmsAdminService;

    @RequestMapping("/login")
    public Map<String,Object> login(@RequestBody UmsAdmin umsAdmin){
        Map<String,Object> res = new HashMap<>();
        log.info(umsAdmin.getUsername() + "------" + umsAdmin.getPassword());
        QueryWrapper<UmsAdmin> wrapper = new QueryWrapper<UmsAdmin>();
        wrapper.eq("username",umsAdmin.getUsername());
        wrapper.eq("password",umsAdmin.getPassword());
        UmsAdmin umsAdminTemp = iUmsAdminService.getOne(wrapper);
        if(null != umsAdminTemp){
            Map<String,String> payload = new HashMap<String,String>();
            payload.put("username",umsAdminTemp.getUsername());
            String token = JWTUtils.getToken(payload);
            res.put("status",200);
            res.put("msg","登录成功");
            res.put("token",token);
        }else{
            res.put("status",300);
            res.put("msg","账号或密码不正确");
        }
        return res;
    }
    //首先jwt必须是验证通过的
    @RequestMapping("/test")
    public Map<String,Object> test(HttpServletRequest request){
        Map<String,Object> res = new HashMap<>();
        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtils.verify(token);
        log.info(verify.getClaim("username").asString());
        res.put("status",true);
        res.put("msg","请求成功,token中的用户信息是："+verify.getClaim("username").asString());
        return res;
    }
}

